<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page
	import="java.util.ArrayList,com.supcon.tinyportal.util.Constants"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="p" uri="http://www.supcon.com/tags/tinyportal"%>

<p:portlet id="LoginPortlet" styleClass="ui-sortable" title="Login Portlet">
<%!
    public boolean authenticate(String username, String password){
        return "michael".equals(username) && "123".equals(password);
    }

    public boolean nameexists(String username){
        return "michael".equals(username);
    }
%>
	<p:handler event="login.partialsubmit">
	  <%
	      String username = request.getParameter("username");
	      session.setAttribute("username", username);
	
	      String submittedField = request.getParameter("login.partialsubmit");
	      if ("username".equals(submittedField) && !nameexists(username)) {
	          ArrayList messages = new ArrayList();
	          String message = "User name not found.";
	          messages.add(message);
	          session.setAttribute("MESSAGES", messages);
	      } else if ("remembername".equals(submittedField)) {
	          System.out.println("Remvalue: " + request.getParameter("remembername"));
	          boolean isRemember = request.getParameter("remembername") != null;
	          if (isRemember) {
	            session.setAttribute("rememberMe", new Boolean(isRemember));
	          } else {
	              session.removeAttribute("rememberMe");
	          }
	      }
	  %>
	</p:handler>
	
	<p:handler event="loginEvent">
		  <%
      // Log out current user first
      session.removeAttribute("USER");

      // Read username and password submitted from dialog form
      String username = request.getParameter("username");
      String password = request.getParameter("password");

      // Store user name in session if needed to redisplay.
      // No need to redisplay password, so it is not stored.
      session.setAttribute("username", username);

      // Log the user in
      if (authenticate(username, password)) {
          session.removeAttribute("username");
          session.setAttribute("USER", username);

      // User accout is not found, generate error messages
      } else {
          ArrayList messages = new ArrayList();
          String message = "Account not found.";
          messages.add(message);
          session.setAttribute("MESSAGES", messages);
      }
  %>
	</p:handler>

	<p:handler event="logoutEvent">
	<%
      // Log out current user first
      session.removeAttribute("USER");
  	%>
	</p:handler>

	<p:prerender />

	<c:if test="${empty sessionScope.USER}">
		<jsp:include page="loginForm.jsp" />
	</c:if>

	<c:if test="${not empty sessionScope.USER}">
		<jsp:include page="logoutForm.jsp" />
	</c:if>

	<%
		session.removeAttribute("MESSAGES");
	%>

</p:portlet>
